/**
 * 
 */
package code.google.qinglan.xml;

import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import code.google.qinglan.file.FileHelper;
import code.google.qinglan.min.CompressUnit;

/**
 * @author wxq
 * 
 */
public class ConfigReader {

	private Query q;

	/**
	 * 
	 */
	public ConfigReader() {
		q = new Query();
	}

	public List<CompressUnit> readConfig(String filePath) {
		q.setDocument((new DocHelper()).readDocument(filePath));
		q.setXpathsel(new XpathSelector());
		return q.queryForObjectList("//unit", new NodeMapper<CompressUnit>() {
			@Override
			public CompressUnit mapRow(Node n, int index) {
				CompressUnit c = new CompressUnit();
				Element e = (Element) n;
				c.setName(e.getAttribute("name"));
				c.setEncode(e.getAttribute("encode"));
				c.setLevel(Integer.parseInt(e.getAttribute("level")));
				c.setTargetName(e.getAttribute("target"));

				NodeList ns = e.getChildNodes();
				FileHelper f = new FileHelper();
				int len = ns.getLength();
				for (int i = 0; i < len; i++) {
					Node node = ns.item(i);
					if (node.getNodeType() == Node.ELEMENT_NODE) {
						Element ele = (Element) node;
						if ("path".equals(ele.getTagName())) {
							f.addListFiles(ele.getTextContent(),
									ele.getAttribute("extension"),
									"1".equals(ele.getAttribute("isdepth")));
						} else if ("file".equals(ele.getTagName())) {
							f.getFileList().add(ele.getTextContent());
						}
					}
				}
				c.setFileListName(f.getFileList());
				return c;
			}
		});
	}
}
